#include "threadPool.h"

int initStack(dirStack_t *dirStack, char *path) {
    bzero(dirStack, sizeof(dirStack_t));
    node_t *pNew = (node_t *)calloc(1, sizeof(node_t));
    memcpy(pNew->data, path, strlen(path));
    pNew->pNext = NULL;
    dirStack->pFront = pNew;
    ++dirStack->size;
    return 0;
}

int initStack2(dirStack_t *dirStack, MYSQL *mysql, char *username) {
    bzero(dirStack, sizeof(dirStack_t));
    node_t *pNew = (node_t *)calloc(1, sizeof(node_t));

    char sql_buf[512] = {0};
    char query_path[] = "select id from file_info where";
    snprintf(sql_buf, sizeof(sql_buf), "%s user = '%s' and filepath = '/' and  tomb = 0;", query_path, username);
    mysql_query(mysql,sql_buf);
    MYSQL_RES *result = mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(result);
    
    strcpy(pNew->data, row[0]);
    pNew->pNext = NULL;
    dirStack->pFront = pNew;
    ++dirStack->size;
    return 0;
}

int enStack(dirStack_t *dirStack, char *path) {
    node_t *pNew = (node_t *)calloc(1, sizeof(node_t));
    memcpy(&pNew->data, path, strlen(path));
    pNew->pNext = dirStack->pFront;
    dirStack->pFront = pNew;
    ++dirStack->size;
    return 0;
}

int deStack(dirStack_t *dirStack) {
    node_t *pCur = dirStack->pFront;
    if(dirStack->size > 1) {
        dirStack->pFront = pCur->pNext;
        free(pCur);
        --dirStack->size;
    }
    return 0;
}

int visitStack(dirStack_t *dirStack, char *ret) {
    char buf[1024];
    node_t *pCur = dirStack->pFront;

    strcpy(ret, ""); // 初始化path为空字符串

    while (pCur) {
        strcpy(buf, "/");
        strcat(buf, pCur->data);
        strcat(buf, ret);
        strcpy(ret, buf);
        pCur = pCur->pNext;
    }

    // 去除末尾多余的斜杠
    if (strlen(ret) > 0 && ret[strlen(ret) - 1] == '/') {
        ret[strlen(ret) - 1] = '\0';
    }

    memmove(ret, ret+1, strlen(ret));

    return 0;
}
